/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * CalKeyBoardPanel.java
 *
 * Created on 2009-7-20, 10:21:35
 */

package cn.ekuma.epos.swing.calc;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.text.NumberFormat;
import javax.swing.ActionMap;
import javax.swing.BorderFactory;
import javax.swing.InputMap;
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.KeyStroke;

/**
 *
 * @author Administrator
 */
public class CalcKeyBoardPanel extends javax.swing.JPanel {
    CalcManger manger;
    String inputText;
    boolean isInputMode;
    NumberFormat format;
    /** Creates new form CalKeyBoardPanel */
    public CalcKeyBoardPanel() {
        
        initComponents();
        manger=new CalcManger();
        initButtonPanel();
        jList1.setModel(manger);
        ActionMap actionMap=new ActionMap();
        setActionMap(actionMap);
        //Ticket managed
        actionMap.put("addOP",getOPAcion(new AddOP()));
        actionMap.put("subOP",getOPAcion(new SubOP()));
        actionMap.put("divOP",getOPAcion(new DivOP()));
        actionMap.put("mulOP",getOPAcion(new MulOP()));

        actionMap.put("MC",getCommAction(new MCCommand()));
        actionMap.put("MR",getCommAction(new MRCommand()));
        actionMap.put("M+",getCommAction(new MAddCommand()));
        actionMap.put("M-",getCommAction(new MSubCommand()));
        actionMap.put("SQRT",getCommAction(new SqrtCommand()));


        actionMap.put("EQ",getCommAction(new EQCommand()));
        actionMap.put("Up",new m_jUpAction());
        actionMap.put("Down",new m_jDownAction());
        actionMap.put("Delete",new m_jDelAction());
        actionMap.put("BackSpace",new m_jBackSpaceAction());
        actionMap.put("Clear",new m_jClearAction());

        InputMap inputMap=new InputMap();
        setInputMap(JPanel.WHEN_FOCUSED, inputMap);
        inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_ADD, 0),"addOP");
        inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_SUBTRACT, 0),"subOP");
        inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_DIVIDE, 0),"divOP");
        inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_MULTIPLY, 0),"mulOP");

        inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_F5, 0),"MC");
        inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_F6, 0),"MR");
        inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_F7, 0),"M+");
        inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_F8, 0),"M-");
        inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_F9, 0),"SQRT");
        inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0),"EQ");

        inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_UP, 0),"Up");
        inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, 0),"Down");
        inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_DELETE, 0),"Delete");
        inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_BACK_SPACE, 0),"BackSpace");
        inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_SPACE, 0),"Clear");

        reset();
    }

    public void reset(){
        isInputMode=true;
        inputText="";
        resetText();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        totalTxt = new javax.swing.JLabel();
        centerPanel = new javax.swing.JPanel();
        buttonsPanel = new javax.swing.JPanel();
        jScrollPane2 = new javax.swing.JScrollPane();
        jList1 = new javax.swing.JList();
        inputPanel = new javax.swing.JPanel();
        inputLabel = new javax.swing.JLabel();
        jlastOPLabel = new javax.swing.JLabel();

        setPreferredSize(new java.awt.Dimension(650, 356));
        addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                formKeyPressed(evt);
            }
        });
        setLayout(new java.awt.BorderLayout());

        totalTxt.setFont(new java.awt.Font("宋体", 0, 18));
        totalTxt.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        totalTxt.setText("jLabel1");
        totalTxt.setBorder(new javax.swing.border.LineBorder(new java.awt.Color(0, 0, 0), 1, true));
        totalTxt.setFocusable(false);
        totalTxt.setRequestFocusEnabled(false);
        add(totalTxt, java.awt.BorderLayout.PAGE_START);
        totalTxt.getAccessibleContext().setAccessibleName("totalTxt");

        centerPanel.setPreferredSize(new java.awt.Dimension(550, 300));
        centerPanel.setLayout(new java.awt.BorderLayout());

        buttonsPanel.setMinimumSize(new java.awt.Dimension(100, 150));
        buttonsPanel.setPreferredSize(new java.awt.Dimension(330, 300));

        javax.swing.GroupLayout buttonsPanelLayout = new javax.swing.GroupLayout(buttonsPanel);
        buttonsPanel.setLayout(buttonsPanelLayout);
        buttonsPanelLayout.setHorizontalGroup(
            buttonsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 330, Short.MAX_VALUE)
        );
        buttonsPanelLayout.setVerticalGroup(
            buttonsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 300, Short.MAX_VALUE)
        );

        centerPanel.add(buttonsPanel, java.awt.BorderLayout.EAST);

        jScrollPane2.setHorizontalScrollBarPolicy(javax.swing.ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);

        jList1.setModel(new javax.swing.AbstractListModel() {
            String[] strings = { "Item 1", "Item 2", "Item 3", "Item 4", "Item 5" };
            public int getSize() { return strings.length; }
            public Object getElementAt(int i) { return strings[i]; }
        });
        jList1.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_INTERVAL_SELECTION);
        jScrollPane2.setViewportView(jList1);

        centerPanel.add(jScrollPane2, java.awt.BorderLayout.CENTER);

        add(centerPanel, java.awt.BorderLayout.CENTER);

        inputPanel.setLayout(new java.awt.BorderLayout());

        inputLabel.setBackground(new java.awt.Color(255, 255, 255));
        inputLabel.setFont(new java.awt.Font("宋体", 0, 24));
        inputLabel.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        inputLabel.setText("jLabel2");
        inputLabel.setBorder(javax.swing.BorderFactory.createEtchedBorder());
        inputLabel.setOpaque(true);
        inputLabel.setPreferredSize(new java.awt.Dimension(60, 33));
        inputPanel.add(inputLabel, java.awt.BorderLayout.CENTER);
        inputLabel.getAccessibleContext().setAccessibleName("inputTxt");

        jlastOPLabel.setFont(new java.awt.Font("宋体", 0, 24));
        jlastOPLabel.setText("jLabel1");
        jlastOPLabel.setBorder(javax.swing.BorderFactory.createEmptyBorder(1, 1, 1, 1));
        jlastOPLabel.setFocusable(false);
        jlastOPLabel.setRequestFocusEnabled(false);
        inputPanel.add(jlastOPLabel, java.awt.BorderLayout.WEST);

        add(inputPanel, java.awt.BorderLayout.SOUTH);
    }// </editor-fold>//GEN-END:initComponents

    private void formKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_formKeyPressed
                char cTrans=evt.getKeyChar();
                cTran(cTrans);
    }//GEN-LAST:event_formKeyPressed

    private void cTran(char cTrans){
        if(!isInputMode){
            isInputMode=true;
            inputText="";
        }
        if (cTrans == '.'&&!inputText.isEmpty()&&!(inputText.lastIndexOf(".")>0))
            inputText+=cTrans;
        if ((cTrans == '0' ||cTrans == '1' || cTrans == '2' || cTrans == '3' || cTrans == '4' || cTrans == '5' || cTrans == '6' || cTrans == '7' || cTrans == '8' || cTrans == '9') ) {
             inputText+=cTrans;
        }
        inputLabel.setText(inputText);
    }


     CalcOPAction getOPAcion(AbstractOP op1){
        return new CalcOPAction(op1);
    }

     CalcCommAction getCommAction(AbstractCommand comm){
         return new CalcCommAction(comm);
     }

    class CalcOPAction extends javax.swing.AbstractAction{
        AbstractOP op;
       public CalcOPAction(AbstractOP op1){
            op=op1;
        }
        @Override
        public void actionPerformed(ActionEvent e) {
           if(isInputMode&&!inputText.isEmpty()){
              double value=Double.parseDouble(inputText);
              manger.addData(value);
           }
           isInputMode=false;
           manger.addOP(op);
           resetText();
        }
    }

   class CalcCommAction extends javax.swing.AbstractAction{
       AbstractCommand command;
       public CalcCommAction(AbstractCommand comm){
           command=comm;
       }

        @Override
        public void actionPerformed(ActionEvent e) {
           if(isInputMode&&!inputText.isEmpty()){
             double value=Double.parseDouble(inputText);
             manger.addData(value);
           }
           isInputMode=false;
           manger.addCommand(command);
           resetText();
        }

   }

   class m_jUpAction extends javax.swing.AbstractAction{
        @Override
        public void actionPerformed(ActionEvent e) {
          int selected=jList1.getSelectedIndex();
          if(selected>0){
              jList1.setSelectedIndex(selected-1);
              jList1.ensureIndexIsVisible(selected);
          }
          else{
              jList1.setSelectedIndex(jList1.getModel().getSize()-1);
              jList1.ensureIndexIsVisible(selected);
          }
        }
   }

   class m_jDownAction extends javax.swing.AbstractAction{
        @Override
        public void actionPerformed(ActionEvent e) {
          int selected=jList1.getSelectedIndex();
          if(selected>=0&&selected<jList1.getModel().getSize()-1){
               jList1.setSelectedIndex(selected+1);
               jList1.ensureIndexIsVisible(selected);
          }
          else{
              jList1.setSelectedIndex(0);
              jList1.ensureIndexIsVisible(selected);
          }
        }
   }

   class m_jDelAction extends javax.swing.AbstractAction{
        @Override
        public void actionPerformed(ActionEvent e) {

        }
   }


    class  m_jBackSpaceAction extends javax.swing.AbstractAction{
        @Override
        public void actionPerformed(ActionEvent e) {
           if(isInputMode&&!inputText.isEmpty()){
              inputText=inputText.substring(0, inputText.length()-1);
              inputLabel.setText(inputText);
           }
        }
    }

    class  m_jClearAction extends javax.swing.AbstractAction{
        @Override
        public void actionPerformed(ActionEvent e) {
           manger.reset();
           reset();
        }
    }

   private void resetText(){
       format=NumberFormat.getNumberInstance();
       double currentValue=manger.getCurrentvalue();
       String txt="∞";
       if(!Double.isNaN(currentValue)){
           txt= format.format(currentValue);
       }
       inputLabel.setText(txt);
       txt=format.format(CalcManger.getMsValue());
       totalTxt.setText(txt);
       int selected=jList1.getModel().getSize()-1;
       jList1.setSelectedIndex(selected);
       jList1.ensureIndexIsVisible(selected);
       jlastOPLabel.setText(manger.getLastOPName());
   }

    private void initButtonPanel() {
        Num numActionListener = new Num();
        buttonsPanel.setLayout(new BorderLayout(10, 3));
        panel1 = new JPanel(new GridLayout(1, 3, 6, 6));
        panel2 = new JPanel(new GridLayout(4, 5, 3, 3));
        panel3 = new JPanel(new GridLayout(5, 1, 3, 3));
        panel4 = new JPanel(new BorderLayout(3, 3));

        addButton(panel1, "Backspace", new m_jBackSpaceAction(), Color.red);
        addButton(panel1, "CE", new m_jClearAction(), Color.red);
        addButton(panel1, "C", new Clear(), Color.red);

        addButton(panel2, "7", numActionListener, Color.blue);
        addButton(panel2, "8", numActionListener, Color.blue);
        addButton(panel2, "9", numActionListener, Color.blue);
        addButton(panel2, "÷", getOPAcion(new DivOP()), Color.red);
        addButton(panel2, "√", getCommAction(new SqrtCommand()), Color.blue);

        addButton(panel2, "4", numActionListener, Color.blue);
        addButton(panel2, "5", numActionListener, Color.blue);
        addButton(panel2, "6", numActionListener, Color.blue);
        addButton(panel2, "×", getOPAcion(new MulOP()), Color.red);
        addButton(panel2, "%", getCommAction(new PerCommand()), Color.blue);

        addButton(panel2, "1", numActionListener, Color.blue);
        addButton(panel2, "2", numActionListener, Color.blue);
        addButton(panel2, "3", numActionListener, Color.blue);
        addButton(panel2, "-", getOPAcion(new SubOP()), Color.red);
        addButton(panel2, "1/x", getCommAction(new XPerCommand()), Color.blue);

        addButton(panel2, "0", numActionListener, Color.blue);
        addButton(panel2, "±", new Clear(), Color.blue);
        addButton(panel2, ".", numActionListener, Color.blue);
        addButton(panel2, "+", getOPAcion(new AddOP()), Color.red);
        addButton(panel2, "=", getCommAction(new EQCommand()), Color.red);

        JButton btns = new JButton("M");
        btns.setBorder(BorderFactory.createLoweredBevelBorder());
        btns.setEnabled(false);
        btns.setPreferredSize(new Dimension(20, 20));

        panel3.add(btns);
        addButton(panel3, "MC", getCommAction(new MCCommand()), Color.red);
        addButton(panel3, "MR", getCommAction(new MRCommand()), Color.red);
        addButton(panel3, "M+", getCommAction(new MAddCommand()), Color.red);
        addButton(panel3, "M-", getCommAction(new MSubCommand()), Color.red);

        panel4.add(panel1, BorderLayout.NORTH);
        panel4.add(panel2, BorderLayout.CENTER);
        buttonsPanel.add(panel3, BorderLayout.WEST);
        buttonsPanel.add(panel4);
    }

    private void addButton(JPanel panel, String name, ActionListener action, Color color) {
        JButton bt = new JButton(name);
        panel.add(bt);
        bt.setFont(new java.awt.Font("SansSerif", 0, 14));
        bt.setForeground(color);
        bt.addActionListener(action);
        bt.setFocusable(false);
        bt.setRequestFocusEnabled(false);
    }

    class Num implements ActionListener {

        public void actionPerformed(ActionEvent e) {
            String srt = e.getActionCommand();
            cTran(srt.charAt(0));
        }
    }

    class Clear implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            String str = e.getActionCommand();
            if (str.equalsIgnoreCase("±")) {
                if(isInputMode&&!inputText.isEmpty()){
                  double i =0- Double.parseDouble(inputText);
                  inputText=String.valueOf(i);
                  inputLabel.setText(format.format(i));
                }else if(!isInputMode){
                    manger.addCommand(new ChangeSignCommand());
                    resetText();
                }
            }else if(str.equalsIgnoreCase("C")) {
                 isInputMode=false;
                 inputText="";
                 inputLabel.setText("0");
            }

        }
    }



    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JPanel buttonsPanel;
    private javax.swing.JPanel centerPanel;
    private javax.swing.JLabel inputLabel;
    private javax.swing.JPanel inputPanel;
    private javax.swing.JList jList1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JLabel jlastOPLabel;
    private javax.swing.JLabel totalTxt;
    // End of variables declaration//GEN-END:variables

    private JPanel panel1, panel2, panel3, panel4;

}
